#!/usr/bin/env node
/**
 * Collects all packages in the repository in a way that makes it
 * easy to process for packaging.
 */
const child_process = require('child_process');
const fs = require('fs-extra');
const path = require('path');

if (process.argv.length < 4) {
  process.stderr.write('Usage: list-packages <jsii file> <nonjsii file>\n');
  process.exit(1);
}

const lerna = path.resolve(__dirname, '..', 'node_modules', '.bin', 'lerna');

child_process.exec(`${lerna} ls --toposort --json`, { shell: true }, (error, stdout) => {
  if (error) {
    console.error('Error: ', error);
    process.exit(-1);
  }
  const modules = JSON.parse(stdout.toString('utf8'));

  const jsiiDirectories = [];
  const nonJsiiNames = [];

  for (const module of modules) {
    const pkgJson = require(path.join(module.location, 'package.json'));
    if (pkgJson.jsii) {
      jsiiDirectories.push(module.location);
    } else {
      nonJsiiNames.push(pkgJson.name);
    }
  }

  fs.writeFileSync(process.argv[2], jsiiDirectories.join('\n'));
  fs.writeFileSync(process.argv[3], nonJsiiNames.join('\n'));
});
